package com.szalay.useradmin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Persistent dictionary.
 */
final class WriteBackDictionary extends Dictionary {
    private final File storage;
    private final Properties properties = new Properties();
    private final String dictionaryName;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    
    WriteBackDictionary(final File storage, final String dictionaryName) {
        this.storage = storage;
        this.dictionaryName = dictionaryName;
        
        //Read properties
        try {
            final File file = new File(storage.getAbsolutePath() + "/" + dictionaryName + ".properties");
            if (file.exists()) {
                final FileInputStream fis = new FileInputStream(file);
                properties.load(fis);
                fis.close();
            }
        }
        catch (IOException e) {
            logger.error(dictionaryName, e);
            throw new IllegalStateException(e);
        }
    }
    
    @Override
    public int size() {
        return properties.size();
    }

    @Override
    public boolean isEmpty() {
        return properties.isEmpty();
    }

    @Override
    public Enumeration keys() {
        return properties.keys();
    }

    @Override
    public Enumeration elements() {
        return properties.elements();
    }

    @Override
    public Object get(Object key) {
        return properties.get(key);
    }

    @Override
    public Object put(Object key, Object value) {
        final Object result = properties.put(key, value.toString());
        store();
        return result;
    }

    @Override
    public Object remove(Object key) {
        final Object result = properties.remove(key);
        store();
        return result;
    }
    
    private synchronized void store() {
        try {
            final File file = new File(storage.getAbsolutePath() + "/" + dictionaryName + ".properties");
            final FileOutputStream out = new FileOutputStream(file);
            properties.store(out, "");
            out.flush();
            out.close();
        }
        catch (IOException e) {
            logger.error(dictionaryName, e);
            throw new IllegalStateException(e);
        }
    }
}
